﻿(function () {

    var drag = {
        selected: null,
        offset: null,
        move: function (e) {
            var mPos = smalljs.mouse.coords(e || window.event);
            if (drag.selected !== null) {
                if (typeof drag.selected.style !== 'undefined') {
                    drag.selected.style.position = 'absolute';
                    var offY = 10, offX = 50;
                    if (window.attachEvent && !window.addEventListener) {
                        // <= IE8
                        offY = 0;
                        offX = 0;
                    }
                    drag.selected.style.top = (mPos.y - drag.offset.y - offY) + 'px';
                    drag.selected.style.left = (mPos.x - drag.offset.x - offX) + 'px';
                }
            }
            return false;
        },
        item: function (id) {
            var leave = function (e) {
                var mPos = smalljs.mouse.coords(e || window.event);
                var pos = smalljs.page.pos(drag.selected);
                var bX = mPos.x, sX = pos.X, bY = pos.Y, sY = mPos.y;
                if (mPos.x > pos.X) {
                    bX = mPos.x;
                    sX = pos.X;
                }

                if (mPos.y > pos.Y) {
                    bY = mPos.y;
                    sY = pos.Y;
                }

                if (((bX - sX) > 100) || ((bY - sY) > 100)) {
                    drag.selected = null;
                }
            };

            if (typeof id !== 'undefined') {

                sj(document).on('mousedown', function (e) {
                    if (drag.selected !== null) {
                        leave(e);
                    }
                });

                sj(id).on('mousedown', function (e) {
                    drag.selected = smalljs.get(id);
                    drag.offset = smalljs.mouse.offset(id, e);
                }).on('mouseup', function () {
                    drag.selected = null;
                }).on('mouseleave', function (e) {
                    if (drag.selected != null) {
                        leave(e);
                    }

                })

                //'Esc' key stops dragging
                sj(document).on('keyup', function (e) {
                    if (window.event) {
                        key = window.event.keyCode;     //IE
                    } else {
                        key = e.which;
                    }
                    if (key === 27) {
                        drag.selected = null;
                    }
                });

                document.onmousemove = drag.move;
            }

        }
    };



    smalljs.extend({
        drag: drag
    });

})();